from django.shortcuts import render
from django.http import HttpResponse, JsonResponse

from .. import models
from django.core.urlresolvers import reverse
from . import viewsIndex

# 订单列表
def orderindex(request):
    # 查询
    data = models.Order.objects.all().values()
    for x in data:
        x['username'] = models.Users.objects.get(id=x['uid_id']).username
    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类
    paginator = Paginator(data,10)

    # 获取当前页码
    p = int(request.GET.get('p',1))

    # 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
    orderlist = paginator.page(p)

    # 分配数据
    context = {'orderlist': orderlist}
    return render(request, 'myadmin/order/index.html', context)

# 订单修改
def orderedit(request):
    if request.method == 'GET':
        status = models.Order.objects.get(id=request.GET.get('gid')).status
        context = {'status': status}
        return render(request, 'myadmin/order/edit.html', context)
    else:
        status = request.POST.get('status')
        # 获取订单
        data = models.Order.objects.get(id=request.POST.get('gid'))
        data.status = status
        data.save()
        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_order_index')+'"</script>')


# 订单删除
def orderdel(request):
    # 获取当前订单
    user = models.Order.objects.get(id=request.GET.get('id'))
    user.delete()

    # 加载模板
    return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_order_index')+'"</script>')